﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using handvn.Models;
using System.IO;


namespace handvn.Controllers
{ 
    public class ProductController : Controller
    {
        private HandvnContext db = new HandvnContext();
        
        private const int PageSize = 20;
        //
        // GET: /Product/
        public ViewResult Index()
        {
            var products = db.Products.Include(p => p.User).Include(p => p.DetailCategories);
            return View(products.ToList());
        }

        //
        // GET: /Product/
        public ViewResult UserView(string UserID)
        {
            //var detailcategory = db.DetailCategory.Where(d => d.CategoryID == DetailCategoryID);
            //return View(detailcategory.ToList());
            var products = db.Products.Where(p => p.UserID == UserID);
            return View(products.ToList());
        }

        public ActionResult View(int decaid, int page=1)
        {
            
            var queryResults1 = db.Products.Where(p => p.TinhTrang == true && p.DetailCategoriesID==decaid);

            ViewBag.TotalPages = (int)Math.Ceiling((double)queryResults1.Count() / PageSize);

            var prod = (from p in db.Products
                        orderby p.SoLuotXem descending
                        where (p.DetailCategoriesID == decaid && p.TinhTrang == true)
                        select p).Skip((page - 1) * PageSize).Take(PageSize).ToList();

            ViewBag.CurrentPage = page;
            ViewBag.PageSize = PageSize;
            ViewBag.did = decaid;
            ViewBag.OnePageOfProducts = prod;

            ////var products = db.Products.Where(p => p.DetailCategoriesID == DetailCategoryID).ToPagedList(currentPageIndex, DefaultPageSize);
           
            //ViewBag.dcid = decaid;
            return View();
           // return PartialView("_ProductView", products);
        }

        //
        // GET: /Product/Details/5
        public ViewResult Details(string id)
        {
            Product product = db.Products.Find(id);
            return View(product);
        }

        //
        // GET: /Product/ViewDetail/5
        public ViewResult ViewDetail(string prod)
        {
            //var products = db.Products.Where(p => p.ProductID == prod);
            var queryResults1 = (from p in db.Products.Include("Images")
                            where (p.ProductID == prod)
                            select p);
            var queryResults2 = db.Images.Where(p => p.ProductID == prod);
            //
            // Update SoLuotXem -------------------------
            Product proView = db.Products.Find(prod);
            proView.SoLuotXem = proView.SoLuotXem + 1;
            db.Entry(proView).State = EntityState.Modified;
            db.SaveChanges();
            //-------------------------------------------
            //return View(products.ToList());
            var model = new ProductView()
            {
                Product = queryResults1.ToList(),
                Images = queryResults2.ToList(),
                //Product = db.Database.SqlQuery<Product>("select top 8 * from Products where TinhTrang='true' ORDER BY  NgayNhapSanPham DESC ").ToList(),
                //ProductView = db.Database.SqlQuery<Product>("select top 8 * from Products where TinhTrang='true' ORDER BY  SoLuotXem DESC ").ToList(),
               
            };
            return View(model);
        }
        //

        //
        // GET: /Product/UserDetails/5
        public ViewResult UserDetails(string id)
        {
            Product product = db.Products.Find(id);
            return View(product);
        }

        //
        // GET: /Product/UserCreate
        public ActionResult UserCreate()
        {
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username");
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc");
            return View();
        }

        //
        // POST: /Product/UserCreate
        [HttpPost, ValidateInput(false)]
        public ActionResult UserCreate(Product model, HttpPostedFileBase file)
        {
            ProductDAO spDAO = new ProductDAO();
            try
            {
                if (spDAO.ktTrung(model) == false)
                {
                    Product sp = new Product();
                    sp.TenSanPham = model.TenSanPham;
                    sp.GiaSanPham = model.GiaSanPham;
                    sp.GiaThiTruong = model.GiaThiTruong;
                    if (file != null)
                    {
                        if (file.ContentLength > 0)
                        {
                            if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
    (file.ContentType == "image/png"))//check allow jpg, gif, png
                            {
                                var fileName = Path.GetFileName(file.FileName);
                                var path = Path.Combine(Server.MapPath("../Images/HinhAnh/"), fileName);
                                file.SaveAs(path);//save image in folder
                               sp.HinhAnh = file.FileName;
                            }
                        }
                    }
                    sp.GioiThieu = model.GioiThieu;
                    sp.SoLuong = model.SoLuong;
                    sp.SoLuotXem = model.SoLuotXem;
                    sp.NgayNhapSanPham = DateTime.Now.ToLocalTime();
                    sp.DetailCategoriesID = model.DetailCategoriesID;
                    sp.UserID = Session["UserId"].ToString();
                    sp.TinhTrang = true;

                    string ngaythang = DateTime.Now.ToLocalTime().ToShortDateString();
                    string[] ngaythangs = ngaythang.Split('/');
                    string gio = DateTime.Now.ToLocalTime().ToLongTimeString();
                    string[] gios = gio.Split(':');
                    sp.ProductID = "SP";
                    foreach (string part in ngaythangs)
                    {
                        sp.ProductID = sp.ProductID + part;
                    }
                    foreach (string part in gios)
                    {
                        sp.ProductID = sp.ProductID + part;
                    }
                    string[] ma = sp.ProductID.Split(' ');
                    sp.ProductID = ma[0];

                    using (var db = new HandvnContext())
                    {
                        db.Products.Add(sp);
                        db.SaveChanges();
                    }
                    return RedirectToAction("UserView", new { UserID = @Session["UserId"] });
                }
                else
                {
                    ViewData["key"] = "Sản phẩm này đã tồn tại";
                    ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", model.UserID);
                    ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", model.DetailCategoriesID);
                    return View(model);
                }
            }
            catch
            {
                return View();
            }
            
        }
        //
        // GET: /Product/Create
        public ActionResult Create()
        {
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username");
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc");
            return View();
        }

        //
        // POST: /Product/Create
        [HttpPost]
        public ActionResult Create(Product model)
        {
            ProductDAO spDAO = new ProductDAO();
            if (spDAO.ktTrung(model) == false)
            {
                Product sp = new Product();
                sp.TenSanPham = model.TenSanPham;
                sp.GiaSanPham = model.GiaSanPham;
                sp.GiaThiTruong = model.GiaThiTruong;
                sp.HinhAnh = model.HinhAnh;
                sp.GioiThieu = model.GioiThieu;
                sp.SoLuong = model.SoLuong;
                sp.SoLuotXem = model.SoLuotXem;
                sp.NgayNhapSanPham = DateTime.Now.ToLocalTime();
                sp.DetailCategoriesID = model.DetailCategoriesID;
                sp.UserID = model.UserID;
                sp.TinhTrang = model.TinhTrang;

                string ngaythang = DateTime.Now.ToLocalTime().ToShortDateString();
                string[] ngaythangs = ngaythang.Split('/');
                string gio = DateTime.Now.ToLocalTime().ToShortTimeString();
                string[] gios = gio.Split(':');
                sp.ProductID = "SP";
                foreach (string part in ngaythangs)
                {
                    sp.ProductID = sp.ProductID + part;
                }
                foreach (string part in gios)
                {
                    sp.ProductID = sp.ProductID + part;
                }
                string[] ma = sp.ProductID.Split(' ');
                sp.ProductID = ma[0];

                using (var db = new HandvnContext())
                {
                    db.Products.Add(sp);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewData["key"] = "Sản phẩm này đã tồn tại";
                ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", model.UserID);
                ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", model.DetailCategoriesID);
                return View(model);
            }
        }
        
        //
        // GET: /Product/Edit/5
        public ActionResult Edit(string id)
        {
            Product product = db.Products.Find(id);
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", product.UserID);
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", product.DetailCategoriesID);
            return View(product);
        }

        //
        // GET: /Product/UserEdit/5
        public ActionResult UserEdit(string id)
        {
            Product product = db.Products.Find(id);
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", product.DetailCategoriesID);
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", product.UserID);
            return View(product);
        }

        //
        // POST: /Product/UserEdit/5

        [HttpPost,ValidateInput(false)]
        public ActionResult UserEdit(Product product, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    if (file.ContentLength > 0)
                    {
                        if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
(file.ContentType == "image/png"))//check allow jpg, gif, png
                        {
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("../../Images/HinhAnh/"), fileName);
                            file.SaveAs(path);//save image in folder
                            product.HinhAnh = file.FileName;
                        }
                    }
                }
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("UserView", new { UserID = @Session["UserId"] });
            }
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", product.UserID);
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", product.DetailCategoriesID);
            return View(product);
        }
        //
        // POST: /Product/Edit/5

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.UserID = new SelectList(db.Users, "UserID", "Username", product.UserID);
            ViewBag.DetailCategoriesID = new SelectList(db.DetailCategories, "DetailCategoriesID", "TenChiTietDanhMuc", product.DetailCategoriesID);
            return View(product);
        }

        //
        // GET: /Product/Delete/5
 
        public ActionResult Delete(string id)
        {
            Product product = db.Products.Find(id);
            return View(product);
        }

        //
        // POST: /Product/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {            
            //Product product = db.Products.Find(id);
            //db.Products.Remove(product);
            //db.SaveChanges();
            //return RedirectToAction("Index");
            Product product = db.Products.Find(id);
            product.TinhTrang = false;
            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("UserView", new { UserID = @Session["UserId"] });
        }

        //
        // GET: /Product/UserDelete/5

        public ActionResult UserDelete(string id)
        {
            Product product = db.Products.Find(id);
            return View(product);
        }

        //
        // POST: /Product/UserDelete/5

        [HttpPost]
        public ActionResult UserDel(Product product)
        {
            Product products = db.Products.Find(product.ProductID);
            products.TinhTrang = false;
            db.Entry(products).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("UserView", new { UserID = @Session["UserId"] });
            //return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}